DOM Elements
In this tutorial we shall see how to access the HTML elements using methods of document object.
There are few ways to access the HTML elements, they are:
Finding element by id
Finding elements by its class name
Finding elements by tag name
Finding elements by selectors
getElementById() method
The getElementById is used to select an element by its id. If the element is found, then it returns the element, else it returns null.
Example
<html>
<head>
<title>JavaScript getElementById() Method</title>
</head>
<body>
<p id="message">ReadersBuddy</p>
</body>
<script>
const para = document.getElementById('message');
console.log(para);
</script>
</html>
Output
<p id="message">ReadersBuddy</p>
In the above example, we have used getElementById method of document to get the para element with id message.
The getElementById will always return single element.
getElementsByTagName() method
The getElementsByTagName method is used to find elements by its element name. Ex. para element.
Example
<html>
<head>
<title>JavaScript getElementsByTagName() Method</title>
</head>
<body>
<p>ReadersBuddy</p>
</body>
<script>
const para = document.getElementsByTagName('p');
console.log(para[0].innerHTML); // ReadersBuddy
</script>
</html>
The getElementsByTagName() method will return a list of elements matching the element. The innerText property of the element is used to get the text inside the element tag.
getElementsByClassName() method
The getElementsByClassName() method is used to select the elements with the class name.
It returns a list of elements matching the class name.
Example
<html>
<head>
<title>JavaScript getElementsByClassName() Method</title>
</head>
<body>
<p class="message">ReadersBuddy</p>
</body>
<script>
const para = document.getElementsByClassName('message');
console.log(para[0].innerHTML); // ReadersBuddy
</script>
</html>
querySelectorAll() method
We can use querySelectorAll() method to select the elements that matches the specified CSS selector.
It can select the elements by its id, class name, attributes, types, values of attributes etc.
Example
<html>
<head>
<title>JavaScript querySelectorAll() Method</title>
</head>
<body>
<p class="message">ReadersBuddy</p>
</body>
<script>
const para = document.querySelectorAll('p.message');
console.log(para[0].innerHTML); // ReadersBuddy
</script>
</html>
querySelector() method
The querySelector() method to selects the first element that matches one or more CSS selectors.
It can also select the elements by its id, class name, attributes, types, values of attributes etc.
Example
<html>
<head>
<title>JavaScript querySelector() Method</title>
</head>
<body>
<p class="message">ReadersBuddy</p>
</body>
<script>
const para = document.querySelector('p.message');
console.log(para.innerHTML); // ReadersBuddy
</script>
</html>